<script setup>

import {Coin, Moon, Sunny, Wallet} from "@element-plus/icons-vue";
import * as echarts from 'echarts';
import {ref} from "vue";
import {ElMessage} from "element-plus";


// 控制抽屉
const drawer = ref(false)
// 充值或提现对话框
const dialogVisible = ref(false)

//充值或提现弹窗标题
const title = ref('')
//提现金额方法
const withdrawals = async () => {
    if (!validateInput()) {
        ElMessage.error('请输入正确的金额数,只能输入两位小数！')
        return;
    }
    // 如果输入有效，则执行提现操作
    const result = await withdrawalsService(input.value)
    ElMessage.success('提现成功')
    // 充值成功后刷新页面
    location.reload();
    dialogVisible.value = false;
}
//充值金额方法
const deposits = async () => {
    if (!validateInput()) {
        ElMessage.error('请输入正确的金额数,只能输入两位小数！')
        return;
    }
    // 如果输入有效，则执行提现操作
    const result = await depositsService(input.value)
    ElMessage.success('充值成功')
    // 充值成功后刷新页面
    location.reload();
    dialogVisible.value = false;

}
//提现或者充值的金额
const input = ref(0);
const validateInput = () => {
    if (!input.value) {
        return false;
    }
    const numericRegex = /^[0-9]+(\.[0-9]{1,2})?$/;//只能输入两位小数
    if (!numericRegex.test(input.value)) {
        return false;
    }
    // 金额是否大于0
    return parseFloat(input.value) > 0;
}
// 账单信息数据模型
const tableData = ref([
    {btime: ''},
    {btype: ''},
    {bamount: ''},
])

import {useUserInfoStore} from '@/store/user.js'
import {billListGetService, billSumGetService, depositsService, withdrawalsService} from "@/api/bill";
import {userInfoGetService} from "@/api/user";

const billSum = ref({
    totalTodayRevenue: 0,//今日收入
    totalMonthRevenue: 0,//本月收入
    totalRevenue: 0//累计收入
})

//获取今日收入、本月收入、累计收入
const billSumGet = async () => {
    const result = await billSumGetService();

    billSum.value.totalTodayRevenue = result.data.totalTodayRevenue;
    billSum.value.totalMonthRevenue = result.data.totalMonthRevenue;
    billSum.value.totalRevenue = result.data.totalRevenue;
    console.log(billSum.value.totalRevenue)
}
billSumGet()//获取收入数据

//获取账单信息
const getBillList = async () => {
    let result = await billListGetService();
    // 更新表格数据
    tableData.value = result.data.map(bill => ({
        // 时间格式转换
        btime: new Date(bill.btime).toLocaleString('en-US', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        }).replace(',', ''),
        // 交易类型转换
        btype: getTypeLabel(bill.btype),
        // 交易金额
        bamount: bill.bamount
    }));
    // 获取最近7天的账单信息
    const endDate = new Date(); // 当前日期
    const startDate = new Date(endDate); // 开始日期为当前日期
    startDate.setDate(startDate.getDate() - 6); // 7天前的日期
    // 过滤出近7天的收入信息
    const recentRevenue = result.data.filter(bill => new Date(bill.btime) >= startDate && bill.btype === 1);

    // 过滤出近7天的提现信息
    const recentPay = result.data.filter(bill => new Date(bill.btime) >= startDate && bill.btype === 3);

    // 调用函数渲染折线图
    renderLineChart_revenue(recentRevenue);
    renderLineChart_pay(recentPay);
};

//图表渲染
const renderLineChart_revenue = (recentData) => {
    const currentDate = new Date();
    // 构建当前日期开始的最近7天日期数组
    const recentXAxisData = [];
    for (let i = 6; i >= 0; i--) {
        const date = new Date(currentDate);
        date.setDate(date.getDate() - i);
        const formattedDate = date.toISOString().slice(0, 10); // 格式化为 YYYY-MM-DD
        recentXAxisData.push(formattedDate);
    }

// 构建当前日期开始的最近7天收入数据数组，如果某天没有账单记录，则收入金额为0
    const recentSeriesData = recentXAxisData.map(date => {
        // 找到所有日期匹配的账单数组
        const matchingBills = recentData.filter(bill => bill.btime.slice(0, 10) === date);
        // 如果有匹配的账单
        if (matchingBills.length > 0) {
            // 使用 reduce 函数累加收入金额
            const totalAmount = matchingBills.reduce((acc, curr) => acc + curr.bamount, 0);
            return totalAmount.toFixed(2);
        } else {
            return 0; // 没有匹配的账单，收入金额为0
        }
    });

    // 使用 ECharts 初始化折线图实例
    const myChart1 = echarts.init(document.getElementById('revenue'));
    myChart1.setOption({
        title: [
            {
                left: 'center',
                text: '近7天收入趋势图'
            }
        ],
        xAxis: {
            type: 'category',
            data: recentXAxisData,
            axisLabel: {
                formatter: function (value) {
                    // 只返回月份和天数
                    return value.slice(5);
                }
            }
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            data: recentSeriesData,
            type: 'line',
            symbol: 'none'
        }],
        lineStyle: {
            width: 3,  // 设置线宽
            color: {
                type: 'linear',  // 渐变类型为线性渐变
                x: 0,  // 渐变起始位置 x 坐标
                y: 0,  // 渐变起始位置 y 坐标
                x2: 0,  // 渐变结束位置 x 坐标
                y2: 1,  // 渐变起始位置 x 坐标
                colorStops: [{
                    offset: 0,  // 渐变起始位置，从 0 开始
                    color: 'red'  // 渐变起始颜色
                }, {
                    offset: 1,  // 渐变结束位置，到 1 结束
                    color: 'yellow'  // 渐变结束颜色
                }]
            }
        },
        tooltip : {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: 'pink'
                }
            }
        }
    });
}
const renderLineChart_pay = (recentData) => {
    const currentDate = new Date();
    // 构建当前日期开始的最近7天日期数组
    const recentXAxisData = [];
    for (let i = 6; i >= 0; i--) {
        const date = new Date(currentDate);
        date.setDate(date.getDate() - i);
        const formattedDate = date.toISOString().slice(0, 10); // 格式化为 YYYY-MM-DD
        recentXAxisData.push(formattedDate);
    }

// 构建当前日期开始的最近7天收入数据数组，如果某天没有账单记录，则收入金额为0
    const recentSeriesData = recentXAxisData.map(date => {
        // 找到所有日期匹配的账单数组
        const matchingBills = recentData.filter(bill => bill.btime.slice(0, 10) === date);
        // 如果有匹配的账单
        if (matchingBills.length > 0) {
            // 使用 reduce 函数累加收入金额
            const totalAmount = matchingBills.reduce((acc, curr) => acc + curr.bamount, 0);
            return totalAmount.toFixed(2);
        } else {
            return 0; // 没有匹配的账单，收入金额为0
        }
    });

    // 使用 ECharts 初始化折线图实例
    const myChart1 = echarts.init(document.getElementById('pay'));
    myChart1.setOption({
        title: [
            {
                left: 'center',
                text: '近7天提现趋势图'
            }
        ],
        xAxis: {
            type: 'category',
            data: recentXAxisData,
            axisLabel: {
                formatter: function (value) {
                    // 只返回月份和天数
                    return value.slice(5);
                }
            }
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            data: recentSeriesData,
            type: 'line',
            symbol: 'none'
        }],
        lineStyle: {
            width: 3,  // 设置线宽
            color: {
                type: 'linear',  // 渐变类型为线性渐变
                x: 0,  // 渐变起始位置 x 坐标
                y: 0,  // 渐变起始位置 y 坐标
                x2: 0,  // 渐变结束位置 x 坐标
                y2: 1,  // 渐变起始位置 x 坐标
                colorStops: [{
                    offset: 0,  // 渐变起始位置，从 0 开始
                    color: 'green'  // 渐变起始颜色
                }, {
                    offset: 1,  // 渐变结束位置，到 1 结束
                    color: 'lightblue'  // 渐变结束颜色
                }]
            }
        },
        tooltip : {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: 'pink'
                }
            }
        }
    });
}

//交易类型转换
const getTypeLabel = (type) => {
    switch (type) {
        case 0:
            return '退款';
        case 1:
            return '收入';
        case 2:
            return '充值';
        case 3:
            return '提现';
        default:
            return '';
    }
};
getBillList()//获取钱包流水

const userInfoStore = useUserInfoStore();//获取个人信息（金额）
//获取个人信息
const getUserInfo = async () => {
    let result = await userInfoGetService();
    //存储pinia
    userInfoStore.info = result.data;
}
getUserInfo()
</script>
<template>
  <!--    //顶部的财务盒子-->
    <div class="wallet_box">
        <!--    上部分-->
        <div style="padding-top: 20px;padding-left: 100px;font-size: 17px">钱包余额</div>
        <div style="padding-left: 30px;margin-top: 5px;padding-bottom: 5px">
            <el-icon size="48px" style="vertical-align:middle">
                <Wallet/>
            </el-icon>
            <div style="display: inline-block;width: 500px;padding-left: 18px;"><span
                    style="font-size: 25px">￥{{ userInfoStore.info.sbalance }}</span></div>
            <el-button type="primary" @click="dialogVisible = true;title='请输入充值金额';input=''">充值</el-button>
            <el-button type="warning" @click="dialogVisible = true;title='请输入提现金额';input=''">提现</el-button>
            <el-link :underline="false" @click="drawer = true"
                     style="color: white;width: 100px;height: 50px; padding-left: 40px;font-size: 18px">钱包记录
            </el-link>
        </div>
        <!--        交易记录的抽屉-->
        <el-drawer v-model="drawer" title="交易记录" :with-header="false"
                   style="color:black;background-color:whitesmoke;"
                   :size="550">
            <el-table :data="tableData" :header-cell-style="{
            textAlign: 'center',
            height: '30px',}" :row-style="{height: '20px'}"
                      style="width: 100%; border-left:pink  solid 3px;border-top: deeppink solid 2px;font-size: 16px; background-color: whitesmoke"
                      size="small"
                      height="560" stripe>
                <el-table-column prop="btime" align="center" label="日期" width="150"/>
                <el-table-column prop="btype" align="center" label="交易" width="160"/>
                <el-table-column prop="bamount" align="center" label="金额">
                    <template v-slot="scope">
                        <span :style="{ color: getAmountColor(scope.row.btype) }">
                             {{
                            (scope.row.btype === "退款") || (scope.row.btype === "提现") ? '-' : ((scope.row.btype === "充值") || (scope.row.btype === "收入") ? '+' : '')
                            }}
                            {{ scope.row.bamount }}
                        </span>
                    </template>
                </el-table-column>
            </el-table>
        </el-drawer>
        <!--   下部分 -->
        <div style="height: 100px;padding-top:35px;padding-left: 30px;">
            <div class="revenue_small_box">
                <el-icon size="50px" style="float: left;vertical-align: middle;color:rgba(14,146,240,0.76) ">
                    <Sunny/>
                </el-icon>
                <span style="font-size: 15px;vertical-align: top;color:rgba(24,24,48,0.59);">今日收入</span>
                <div style="width: 200px;padding-left: 18px;vertical-align: middle;color:rgba(14,146,240,0.76);font-size: 18px; ">
                    ￥{{ billSum.totalTodayRevenue }}
                </div>
            </div>

            <div class="revenue_small_box">
                <el-icon size="50px" style="float: left;vertical-align: middle;color:rgba(14,146,240,0.76) ">
                    <Moon/>
                </el-icon>
                <span style="font-size: 15px;vertical-align: top;color:rgba(24,24,48,0.59);">本月收入</span>
                <div style="width: 200px;padding-left: 18px;vertical-align: middle;color:rgba(14,146,240,0.76);font-size: 18px; ">
                    ￥{{ billSum.totalMonthRevenue }}
                </div>
            </div>

            <div class="revenue_small_box">
                <el-icon size="50px" style="float: left;vertical-align: middle;color:rgba(14,146,240,0.76) ">
                    <Coin/>
                </el-icon>
                <span style="font-size: 15px;vertical-align: top;color:rgba(24,24,48,0.59);">累计收入</span>
                <div style="width: 200px;padding-left: 18px;vertical-align: middle;color:rgba(14,146,240,0.76);font-size: 18px; ">
                    ￥{{ billSum.totalRevenue }}
                </div>
            </div>
        </div>
        <!--    折线图-->
    </div>
    <div id="revenue" style="margin-top:120px;margin-left:40px;display:inline-block;width: 45%;height: 300px;">
        收入折线图
    </div>
    <div id="pay" style="margin-top:120px;margin-left:10px;display:inline-block;width: 45%;height: 300px;">
        支出折线图
    </div>

  <!--        提现金额输入框-->
    <el-dialog
            v-model="dialogVisible"
            :title="title"
            width="500"
            :before-close="handleClose"
    >
        <el-input v-model="input" style="width:350px" plain/>
        <template #footer>
            <div>
                <span class="dialog-footer">
            <el-button @click="dialogVisible = false;">取消</el-button>
            <el-button type="primary" @click="title==='请输入提现金额'?withdrawals():deposits ()"> 确认 </el-button>
        </span>
            </div>
        </template>
    </el-dialog>
</template>

<script>
export default {
    name: "FinancialManagement_S",
    methods: {
        getAmountColor(type) {
            switch (type) {
                case "支出": //支出
                case "提现": //提现
                    return 'black';
                case "收入": //收入
                case "充值": //充值
                    return 'orange';
                default:
                    return 'inherit';
            }
        }
    }
}
</script>

<style scoped>
.wallet_box {
    margin: 0 auto;
    margin-top: 10px;
    width: 560px;
    height: 70px;
    background-color: rgba(14, 146, 240, 0.76);
    border-radius: 10px;
    color: white;
}

.el-button {
    background-color: white;
    color: deepskyblue;
    height: 30px;
    width: 55px;
}

/*收入的三个小方块的总结*/
.revenue_small_box {
    height: 50px;
    width: 25%;
    /*background-color: #cccccc;*/
    display: inline-block;
    margin-left: 38px;

}
</style>
